<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>新闻首页</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .category-card {
            margin-bottom: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .nav-section {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
        }
        .user-info {
            color: rgba(255,255,255,0.8);
            margin-left: auto;
            padding-right: 1rem;
        }
        .user-info span {
            color: white;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container">
            <a class="navbar-brand" href="#">新闻系统</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="root_home.html">首页</a>
                    </li>
                </ul>
                <!-- 用户信息展示 -->
                <div class="user-info" id="userInfo"></div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <aside class="col-md-3">
                <div class="nav-section">
                    <h5>新闻分类</h5>
                    <div class="list-group" id="categoryNav">
                        <a href="#" class="list-group-item list-group-item-action active">全部</a>
                    </div>
                </div>
            </aside>

            <main class="col-md-9">
                <section class="category-card">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h4 id="categoryTitle">全部新闻</h4>
                        </div>
                        <div class="card-body" id="newsContainer">
                            <div class="text-center py-5">
                                <div class="spinner-border text-primary"></div>
                                <div class="mt-2 text-muted">正在加载新闻数据...</div>
                            </div>
                        </div>
                    </div>
                </section>
            </main>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Cookie处理函数
        function getCookie(name) {
            return document.cookie
                .split('; ')
                .find(row => row.startsWith(name + '='))
                ?.split('=')[1] || '';
        }

        // 显示用户信息
        function showUserInfo() {
            const username = decodeURIComponent(getCookie('user_name'));
            const userInfo = document.getElementById('userInfo');
            userInfo.innerHTML = username 
                ? `<span>${username}</span>您好` 
                : '';
        }

        async function fetchNews() {
            try {
                const response = await fetch('/get_news');
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);

                const rawData = await response.json();
                const newsArray = Object.values(rawData);

                return {
                    data: newsArray.map(item => ({
                        id: item.news_id,
                        title: item.news_title,
                        class: item.news_class,
                        content: item.news_content || ""
                    })),
                    error: null
                };
            } catch (error) {
                return {
                    data: [],
                    error: error.message
                };
            }
        }

        function renderCategoryNav(newsData) {
            const navContainer = document.getElementById('categoryNav');
            const categories = [...new Set(newsData.map(n => n.class))];
            
            navContainer.innerHTML = `
                <div class="list-group shadow">
                    <div class="list-group-item bg-light border-0 text-muted small">
                        新闻分类（共 ${categories.length} 类）
                    </div>
                    <a href="#全部" class="list-group-item list-group-item-action active">
                        全部（${newsData.length}）
                    </a>
                    ${categories.map(cat => `
                        <a href="#${cat}" 
                        class="list-group-item list-group-item-action"
                        data-class="${cat}">
                            ${cat}（${newsData.filter(n => n.class === cat).length}）
                        </a>
                    `).join('')}
                </div>
            `;
        }

        function renderNews(newsData, categoryName) {
            const container = document.getElementById('newsContainer');
            const titleElement = document.getElementById('categoryTitle');
            
            titleElement.innerHTML = `
                <i class="bi bi-newspaper me-2"></i>
                ${categoryName === '全部' ? '全部新闻' : categoryName}
                <small class="text-muted ms-2">共 ${newsData.length} 条</small>
            `;

            container.innerHTML = newsData.map(news => `
                <div class="card mb-2">
                    <div class="card-body py-2">
                        <a href="normal_display_news.html?news_id=${news.id}" 
                        class="stretched-link text-decoration-none">
                            ${news.title}
                        </a>
                        <span class="badge bg-primary float-end">${news.class}</span>
                    </div>
                </div>
            `).join('');
        }

        window.onload = async () => {
            showUserInfo();
            
            const { data, error } = await fetchNews();
            if (error) {
                document.getElementById('newsContainer').innerHTML = `
                    <div class="alert alert-danger mt-4">
                        <i class="bi bi-exclamation-circle"></i>
                        数据加载失败：${error}
                    </div>`;
                return;
            }

            const categories = [...new Set(data.map(n => n.class))];
            renderCategoryNav(data);
            renderNews(data, '全部');

            document.getElementById('categoryNav').addEventListener('click', e => {
                e.preventDefault();
                if (e.target.tagName === 'A') {
                    document.querySelectorAll('#categoryNav a.active').forEach(link => link.classList.remove('active'));
                    e.target.classList.add('active');
                    const category = e.target.dataset.class || '全部';
                    renderNews(category === '全部' ? data : data.filter(n => n.class === category), category);
                }
            });
        };
    </script>
</body>
</html>